#!/usr/bin/env python
# -*- coding: utf-8 -*-
'''
Author: your name
Date: 2021-09-15 09:27:08
LastEditTime: 2021-09-15 13:27:19
LastEditors: Please set LastEditors
Description: In User Settings Edit
FilePath: \kmoke\smart_qtwidgets\tab_widget.py
'''
#!/usr/bin/env python
# coding=utf-8

from qtpy import QtWidgets, QtCore
from .ui.tab_widget import Ui_Form


class TabWidget(QtWidgets.QWidget):
    current_changed = QtCore.Signal(int)
    def __init__(self, parent=None):
        super(TabWidget, self).__init__(parent)
        self._ui = Ui_Form()
        self._ui.setupUi(self)
        self.__group = QtWidgets.QButtonGroup(self)
        self.__ids = []
        self.__group.setExclusive(True)
        self.__group.buttonClicked.connect(self.__on_tab_changed)
    

    def set_tab_style_sheet(self, style):
        self._ui.tab_bar.setStyleSheet(style)

    def add_extend_widget(self, widget):
        self._ui.tab_extend_layout.addWidget(widget)
    def tab_bar(self):
        return self._ui.tab_bar

    def set_margins(self, left,top,right,bottom):
        self._ui.tab_layout.setContentsMargins(left,top,right,bottom)

    def set_spacing(self, spacing):
        self._ui.tab_layout.setSpacing(spacing)

    def set_tab_bar_margins(self, left,top,right,bottom):
        self._ui.tab_bar_layout.setContentsMargins(left,top,right,bottom)

    def set_tab_button_spacing(self, spacing):
        self._ui.tab_button_layout.setSpacing(spacing)

    def __on_tab_changed(self, btn):
        index = self.__group.id(btn)
        self._ui.stackedWidget.setCurrentIndex(index)
        self.current_changed.emit(index)

    def current_widget(self):
        return self._ui.stackedWidget.currentWidget()

    def add_tab(self, text, widget):
        

        btn = QtWidgets.QPushButton(text, self)
        _w = btn.fontMetrics().width(text) + 30
        btn.setMinimumWidth(_w)
        id = len(self.__ids)
        btn.setCheckable(True)
        self.__group.addButton(btn, id)
        self._ui.stackedWidget.addWidget(widget)
        self.__ids.append(id)
        self._ui.tab_button_layout.addWidget(btn)
        _cid = self.__group.checkedId()
        if _cid == -1:
            _btn = self.__group.button(self.__ids[0])
            _btn.setChecked(True)

